import axios from "axios";
import store from "@/store";
import router from "@/router/index";
import { Toast } from "vant";

const config = require("../../config");
const baseURL = config[process.env.NODE_ENV].baseUrl;
const service = axios.create({
  baseURL,
  timeout: 5000,
});

service.interceptors.request.use(
  (config) => {
    config.headers = {
      token: store.getters.userInfo.token,
    };
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (res) => {
    if (res.data.code == 1000) {
      //正常
      return res.data;
    } else if (res.data.code == 1001 || res.data.code == 2004) {
      //token失效
      Toast.fail({
        message: res.data.msg,
        duration: 1000,
      });
      store.commit("user/setLogout");
      router.push("/home");
    } else {
      Toast.fail({
        message: res.data.msg,
        duration: 1000,
      });
      //其他异常
      return Promise.reject(res);
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default service;
